#include "DBToolPanel.h"
#include <wx/stdpaths.h>
#include <wx/filename.h>

BEGIN_EVENT_TABLE(DBToolPanel, MainPanel)
//	EVT_BUTTON(ID_MAIN_OK, DBToolPanel::OnOK)
END_EVENT_TABLE()


enum {TUXEDOSITE, WEBLOGICSITE } SITE;

wxString rectime_list_column[] = {
	wxT("Record Order"),
	wxT("Record From"),
	wxT("Records Number"),
	wxT("")
};

DBToolPanel::DBToolPanel( wxWindow* parent )
	: MainPanel( parent )
{
	InitControl();
	nRecInterval[0] = -1;
	nRecInterval[1] = -1;

}

DBToolPanel::~DBToolPanel()
{
	dbWrapper.DBClose();
}

void DBToolPanel::OnOK( wxCommandEvent& event )
{
	Close();
}

void DBToolPanel::SetDBFile( wxString fileName )
{
	strDatabaseFile = fileName;
	ParserDB();
}

int DBToolPanel::InitControl()
{
	wxInt16 SvrCount = 0;
	wxInt32 nWidth, nHeight = 0;

	long tmp = 0;

	wxListItem itemCol;

	// Server List Init
	for ( int i = 0; !rectime_list_column[i].IsEmpty(); i ++ ) {
		itemCol.SetText(rectime_list_column[i]);
		m_listRecTimes->InsertColumn(i, itemCol);
	};

	m_listRecTimes->GetSize( &nWidth, &nHeight );
	for( int i = 0; i< m_listRecTimes->GetColumnCount(); i ++ ) {
		m_listRecTimes->SetColumnWidth(i, nWidth/3.5 );
	}


	return -1;
}

int DBToolPanel::ParserDB()
{
	int tableflag = 0;

	dbWrapper.DBOpen( strDatabaseFile, 0 );

	if( dbWrapper.TableExist( wxT("sitelist") ) == 1 ) { //Its' System Database
		wxMessageBox(wxT("Sorry, this file is a FusionSpy system database. Please select an user database."));
		return -1;
	} else if( dbWrapper.TableExist( wxT("tuxresource") ) == 1 ) { //It's Site Database
		tableType = 0;
	} else if( dbWrapper.TableExist( wxT("wlsresource") ) == 1 ) { //It's Site Database
		tableType = 1;
	} else { //It's not a FusionSpy associated database
		wxMessageBox(wxT("Sorry, maybe the file is not an FusionSpy database."));
		return -1;
	}

	UpdateControl();
	return 1;
}

void DBToolPanel::UpdateControl()
{
	wxString strExportDBFile;
	wxString strRecTime, strNextRecTime;
	wxInt32 nRecCount = 0, nRecNumber = 0;

	wxString tabletype_list[]= {
		wxT("TUXEDO SITE"),
		wxT("WEBLOGIC SITE"),
		wxT("")
	};
//	int nCount = dbWrapper.GetRecordCountAndType(&tableType);

	strRecTimeArray.Empty();
	strRecTimeArray = dbWrapper.GetRecordTimeList();
	wxString strRecBegin, strRecEnd;

	m_txtDBFileName->Clear();
	m_txtDBFileName->WriteText( strDatabaseFile );


	m_txtDBTableType->Clear();
	m_txtDBTableType->WriteText(tabletype_list[tableType]);

	m_txtDBRecTimes->Clear();

	nRecCount = (wxInt32)strRecTimeArray.GetCount();
	m_txtDBRecTimes->WriteText( wxString::Format(wxT("%d"), nRecCount) );

	m_listRecTimes->DeleteAllItems();
	for( int i = 0, j = 0; i < nRecCount ; i ++ ) {
		strRecTime = strRecTimeArray.Item(i);
		if( (i +1) < nRecCount ) {
			strNextRecTime = strRecTimeArray.Item(i+1);
		} else {
			strNextRecTime = wxT("N/A");
		}
		long tmp = m_listRecTimes->InsertItem( j, wxString::Format(wxT("%d"), i) );
		m_listRecTimes->SetItemData( tmp, j );

		nRecNumber = dbWrapper.GetRecordNumber( strRecTime, strNextRecTime, tableType);

		m_listRecTimes->SetItem(j, 1, strRecTime);
		m_listRecTimes->SetItem(j, 2, wxString::Format(wxT("%d"), nRecNumber));

		j ++;
	}
}

void DBToolPanel::OnListItemSelected( wxListEvent& event )
{
	//wxMessageBox(wxString::Format("%i",(int)(event.GetIndex())));  
	int CurrSelected = (int)(event.GetIndex());

	if( m_listRecTimes->GetSelectedItemCount() == 1 )  {
		nRecInterval[0] = CurrSelected; nRecInterval[1] = -1;
		return;
	}

	if( nRecInterval[0] == CurrSelected || nRecInterval[1] == CurrSelected ) return;

	if ( nRecInterval[0] == -1 ) {
		nRecInterval[0] = CurrSelected;
		return;
	}

	if ( nRecInterval[1] == -1 ) {
		if( nRecInterval[0] < CurrSelected )
			nRecInterval[1] = CurrSelected;
		else {
			nRecInterval[1] = nRecInterval[0];
			nRecInterval[0] = CurrSelected;
		}
		return;
	}

	if( CurrSelected > nRecInterval[0] && CurrSelected < nRecInterval[1] )
		nRecInterval[1] = CurrSelected;
	
	if( CurrSelected < nRecInterval[0] )
		nRecInterval[0] = CurrSelected;

	if( CurrSelected > nRecInterval[1] )
		nRecInterval[1] = CurrSelected;

	return;

}


void DBToolPanel::OnBtnRun( wxCommandEvent& event)
{
	wxString strRecTime1, strRecTime2;
	wxString strInfoMsg;

	if( strDatabaseFile.IsEmpty() ) {
		wxMessageBox(wxT("Choose a FusionSpy Database file first please!"));
		return;
	}

	if( m_listRecTimes->GetSelectedItemCount() == 0 )  {
		wxMessageBox(wxT("Choose a Record from Record-List first please!"));
		m_listRecTimes->SetFocus();
		return;
	}

	strRecTime1 = strRecTimeArray.Item(nRecInterval[0]);
	strInfoMsg = wxString::Format(wxT("Analyzing data monitored IN [%s] ?"), strRecTime1 );
	if( nRecInterval[1] != -1 ) {
		strRecTime2 = strRecTimeArray.Item(nRecInterval[1]);
		strInfoMsg = wxString::Format(wxT("Analyzing data monitored FROM [%s] TO [%s] ?"), strRecTime1, strRecTime2 );
	}
	
	if( wxMessageBox( strInfoMsg, wxT("FusionSpy"), wxYES_NO ) == wxYES ) {
		CreateReportDir();
		DoAnalyzing( strRecTime1, strRecTime2 );
	}
	return;
}

int DBToolPanel::CreateReportDir()
{
	size_t nPos = 0;
	nPos = strDatabaseFile.find_last_of(wxT("\\"));
	wxString TmpFileName = strDatabaseFile.Right( strDatabaseFile.Length() - nPos - 1  );
	nPos = TmpFileName.find_last_of(wxT("."));
	wxString DbFilename = TmpFileName.Left(nPos);
	wxString StdDataDir = wxStandardPaths::Get().GetDataDir();
	
	strRptDir = StdDataDir + wxT("\\reports\\") + DbFilename;

	wxFileName dirname = wxFileName::DirName( strRptDir );
	if( dirname.DirExists() ) {
		wxString strInfoMsg = wxString::Format( wxT("%s already existed, remove it?"), strRptDir );
		if( wxMessageBox( strInfoMsg, wxT("FusionSpy"), wxYES_NO ) == wxYES ) {
			if( dirname.Rmdir() ) dirname.Mkdir();
		}
	} else {
		dirname.Mkdir();
	}

	jsonWrapper.SetReportDir( strRptDir );

	return 1;
}

void DBToolPanel::DoAnalyzing(wxString rectime1, wxString rectime2)
{
	wxString strSqlPart;
	wxInt32 nCount = 0;
	TuxResourceArray tuxresarray;
	TuxedoClientArray tuxcltarray;
	TuxedoQueueArray tuxquearray;

	WlsResourceArray wlsresarray;
	SysResourceArray sysresarray;
	RptTuxClientArray rpttuxcltarray;
	RptTuxQueueArray rpttuxquearray;
	RptTuxClient rpttuxclt;
	RptTuxQueue rpttuxque;

	tuxresarray.Empty();
	wlsresarray.Empty();
	sysresarray.Empty();

	if( rectime2.IsEmpty() ) {
		strSqlPart = wxString::Format( wxT(" where  RecTime >= '%s';"), rectime1 );
	} else {
		strSqlPart = wxString::Format(wxT(" where  RecTime between '%s' and '%s';"), rectime1, rectime2 );
	}

	if( tableType == TUXEDOSITE ) {
		//Query Resource List
#if 1
		dbWrapper.TuxResListQuery( strSqlPart, &tuxresarray );
		for( int i = 0; i < (wxInt32)tuxresarray.GetCount(); i ++ ) {
			sysresarray.Add( tuxresarray.Item(i).sysresource );
		}
#endif		
		//Query Client List
#if 1
		dbWrapper.TuxCltLstQuery( strSqlPart, &tuxcltarray );
		nCount = (wxInt32)tuxcltarray.GetCount();
		for ( int i = 0; i < nCount; i ++ ) {
			TuxedoClient tuxclt = tuxcltarray.Item(i);
			
			if( rpttuxclt.RecTime == tuxclt.RecTime ) {
				if( tuxclt.Status == wxT("BUSY") )
					rpttuxclt.BusyClient ++ ;
				rpttuxclt.TotalClient ++;
			} else { // New
				if( ! rpttuxclt.RecTime.IsEmpty() ) 
					rpttuxcltarray.Add( rpttuxclt );

				rpttuxclt.RecTime = tuxclt.RecTime;
				rpttuxclt.Flag = 0;
				rpttuxclt.BusyClient = 0;
				rpttuxclt.TotalClient = 0;
				if( tuxclt.Status == wxT("BUSY") )
					rpttuxclt.BusyClient ++ ;
				rpttuxclt.TotalClient ++;
			}
		}
#endif
		//Query Queued List 2009.05.28 Dragon Boat Festival.
#if 1
		dbWrapper.TuxQueLstQuery( strSqlPart, &tuxquearray );
		nCount = (wxInt32)tuxcltarray.GetCount();
		for ( int i = 0; i < nCount; i ++ ) {
			TuxedoQueue tuxque = tuxquearray.Item(i);
			
			if( rpttuxque.RecTime == tuxque.RecTime ) {
				if( wxAtoi(tuxque.Queued) != 0 )
					rpttuxque.BusySvr ++ ;
				rpttuxque.TotalQueued += wxAtoi(tuxque.Queued);
			} else { // New
				if( ! rpttuxque.RecTime.IsEmpty() ) 
					rpttuxquearray.Add( rpttuxque );

				rpttuxque.RecTime = tuxque.RecTime;
				rpttuxque.Flag = 0;
				rpttuxque.BusySvr = 0;
				rpttuxque.TotalQueued = 0;
				if( wxAtoi(tuxque.Queued) != 0 )
					rpttuxque.BusySvr ++ ;
				rpttuxque.TotalQueued += wxAtoi(tuxque.Queued);
			}
		}
#endif
	} else if ( tableType == WEBLOGICSITE ) {
		dbWrapper.WlsResListQuery( strSqlPart, &wlsresarray );
		for( int i = 0; i < (wxInt32)wlsresarray.GetCount(); i ++ ) {
			sysresarray.Add( wlsresarray.Item(i).sysresource );
		}
	}

	jsonWrapper.InitialReportDir(tableType); // Do jsonWrapper Initialiate. copy template.
	if( tableType == TUXEDOSITE ) {
		jsonWrapper.DrawTuxClientData( rpttuxcltarray );
		jsonWrapper.DrawTuxQueueData( rpttuxquearray );

	} else if ( tableType == WEBLOGICSITE ) {
	}

	jsonWrapper.DrawCPUData(sysresarray);
	jsonWrapper.DrawMEMData(sysresarray);

	//wxMessageBox(wxT("Done!"));

	wxString strRptFile = strRptDir + wxT("\\index.htm");
	strRptFile  = wxT("explorer \"") + strRptDir + wxT("\"");

	//wxLaunchDefaultBrowser( strRptFile );
	wxExecute( strRptFile );
}

#include "wx/arrimpl.cpp"
WX_DEFINE_OBJARRAY(RptTuxClientArray);
WX_DEFINE_OBJARRAY(RptTuxQueueArray);